package com.piik.mall.ware.service.impl;

import com.piik.common.constant.WareConstant;
import com.piik.mall.ware.entity.PurchaseDetailEntity;
import com.piik.mall.ware.service.PurchaseDetailService;
import com.piik.mall.ware.service.WareSkuService;
import com.piik.mall.ware.vo.MergeVO;
import com.piik.mall.ware.vo.PurchaseDoneVO;
import com.piik.mall.ware.vo.PurchaseItemDoneVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.piik.common.utils.PageUtils;
import com.piik.common.utils.Query;

import com.piik.mall.ware.dao.PurchaseDao;
import com.piik.mall.ware.entity.PurchaseEntity;
import com.piik.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService detailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        // 检索关键词
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and(w->{
                w.eq("id",key).or().eq("assignee_id",key).or().like("assignee_name",key);
            });
        }
        // 状态
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("status",status);
        }

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


    /**
     * 查询采购单状态为 “新建” 或者 “已分配” 的采购单信息
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils listUnreceive(Map<String, Object> params) {

        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }


    /**
     * 完成采购需求合单操作
     *
     * @param mergeVo
     * @return
     */
    @Transactional
    @Override
    public Integer merge(MergeVO mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if(purchaseId==null ){
            // 新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        // 判断采购单的状态,只能是新建和已分配的才能合单,如果是其他状态 就不能合单了
        PurchaseEntity purchaseEntity = this.getById(purchaseId);
        if(purchaseEntity.getStatus()>WareConstant.PurchaseStatusEnum.RECEIVE.getCode()){
           return -1;
        }

        // 整合菜单需求单
        List<Long> items = mergeVo.getItems();
        final Long  pId = purchaseId;
        List<PurchaseDetailEntity> list = items.stream().map(pdId -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            // 更新每一条 需求单的 采购单编号
            detailEntity.setId(pdId);
            detailEntity.setPurchaseId(pId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).filter(pdId->{
            PurchaseDetailEntity purchaseDetailEntity = detailService.getById(pdId);

            // 采购需求状态 新建 已分配重新分配
            if(purchaseDetailEntity.getStatus()<WareConstant.PurchaseDetailStatusEnum.BUYING.getCode()){
                return true;
            }
            return false;
        }).collect(Collectors.toList());

        if(list != null && list.size()>0){
            detailService.updateBatchById(list);
        }

        // 更新对应的采购单更新时间
        PurchaseEntity entity = new PurchaseEntity();
        entity.setId(purchaseId);
        entity.setUpdateTime(new Date());
        this.updateById(entity);
        return 1;
    }

    /**
     * 领取采购单
     * @param ids
     * @return
     */
    @Transactional
    @Override
    public void receive(List<Long> ids) {

        // 1.领取的采购单的状态只能是新建或者已分配的采购单 其他的是不能领取的
        List<PurchaseEntity> list = ids.stream().map(id -> {
            return this.getById(id);
        }).filter(item -> {
            if (item.getStatus() < WareConstant.PurchaseStatusEnum.RECEIVE.getCode()) {
                return true;
            }
            return false;
        }).map(item -> {
            // 更新领取时间
            item.setUpdateTime(new Date());
            // 更新采购单状态 已领取
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return item;
        }).collect(Collectors.toList());

        // 2.更新采购单状态 已领取
        this.updateBatchById(list);
        // 3.更新采购项的状态为 正在采购
        for(Long id : ids){
           // 根据采购单id 找到对应的采购项对象
            List<PurchaseDetailEntity> entityList = detailService.listDetailByPurchaseId(id);
            List<PurchaseDetailEntity> entities = entityList.stream().map(entity -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(entity.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());

            // 批量更新采购项状态 正在采购
            detailService.updateBatchById(entities);
        }
    }

    /**
     * 完成采购
     *
     * @param vo
     */
    @Transactional
    @Override
    public void done(PurchaseDoneVO vo) {
        // 1. 更采购单状态 已完成
        Boolean flag =true; // 记录采购状态 默认 完成

        // 获取所有的采购项
        List<PurchaseItemDoneVO> items = vo.getItems();
        List<PurchaseDetailEntity> list = new ArrayList<>();
        for(PurchaseItemDoneVO item:items){
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
               // 该采购项采购出现了问题
                flag = false;
                detailEntity.setStatus(item.getStatus());
           }else{
                //采购项采购成功
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());


                // 根据采购项编码查询出对应的采购项详情
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());
                // 3.将采购成功的采购项进行入库操作
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());

            }
            detailEntity.setId(item.getItemId());
            list.add(detailEntity);
        }

        // 批量更新采购项状态
        detailService.updateBatchById(list);

        // 2.更新采购项状态 已完成
        PurchaseEntity entity = new PurchaseEntity();
        entity.setId(vo.getId());
        // 根据采购项成功与失败,更新状态
        entity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode()
                :WareConstant.PurchaseStatusEnum.HASERROR.getCode());
         entity.setUpdateTime(new Date());
         this.updateById(entity);
    }
}